package com.sky.controller.User;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userdishcontroller")
@Slf4j
@RequestMapping("/user/dish")
public class DishController {

    @Autowired
    public DishService dishService;
    //注入redis数据库对象
    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 用户端根据分类id查询菜品及口味  只查询在售状态下的菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishVO>> getByCategoryIdList(Long categoryId){
        log.info("前端传过来的分类id为:{}",categoryId);
        //redis里面存的key值
        String key = "dish_" +categoryId;
        //先到redis中查找 如果有数据 则直接返回  返回的数据是存入到数据库的数据类型
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if (dishVOList != null && dishVOList.size() !=0){
            return Result.success(dishVOList);
        }
        //redis数据库中没有查到 则到sql数据库中查找
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
         dishVOList =  dishService.getByCategoryIdList(dish);
         //再把数据缓存到redis中去
        redisTemplate.opsForValue().set(key,dishVOList);
        return Result.success(dishVOList);
    }


}
